﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using HREDU.Hoang_Tuan.Classes;

namespace HREDU.Hoang_Tuan
{
    public partial class frmDIADANH : Form
    {
        private ListViewColumnSorter lvwColumnSorter;
        public Form fCallForm;
        public string nhomCha = "";
        const byte CtrlMask = 8;
        private string name  ="";

        //Dau vao ten cac column se xu ly trong treeview va listview
        private const string tableName = CDIADANHCollection.tableName;
        private const string nhomColumnName = CDIADANHCollection.nhomColumnName;
        private const string tenColumnName = CDIADANHCollection.tenColumnName;
        private const string cuoiColumnName = CDIADANHCollection.cuoiColumnName;
        private const string khacColumnName = CDIADANHCollection.khacColumnName;
        private const int lenNhom = CDIADANHCollection.lenNhom;
        //private const string maNhom = CDIADANHCollection.maNhom;

        #region "New"
        public frmDIADANH()
        {

            // This call is required by the Windows Form Designer.
            InitializeComponent();
            
            //An button chon vi mo truc tiep frmDIADANH
            this.btnChon.Visible = false;

            InitControls();
        }

        public frmDIADANH(Form frmCall)
        {

            // This call is required by the Windows Form Designer.
            InitializeComponent();

            //Save parent form
            fCallForm = frmCall;

            InitControls();
        }

        public void InitControls()
        {
            // Add any initialization after the InitializeComponent() call.
            name = "Tỉnh thành";
            this.Text = "Danh mục" + name;

            // Create an instance of a ListView column sorter and assign it
            // to the ListView control.
            lvwColumnSorter = new ListViewColumnSorter();
            this.lvControl.ListViewItemSorter = lvwColumnSorter;

            //Add events
            //contextMenuStrip1
            this.QuayLạiToolStripMenuItem.Click += new System.EventHandler(this.QuayLạiToolStripMenuItem_Click);
            this.ThêmNhómToolStripMenuItem.Click += new System.EventHandler(this.ThêmNhómToolStripMenuItem_Click);
            this.ThêmChitiếtToolStripMenuItem.Click += new System.EventHandler(this.ThêmChitiếtToolStripMenuItem_Click);
            this.XóaToolStripMenuItem.Click += new System.EventHandler(this.XóaToolStripMenuItem_Click);
            this.CậpNhậtToolStripMenuItem.Click += new System.EventHandler(this.CậpNhậtToolStripMenuItem_Click);
            this.TìmKiếmToolStripMenuItem.Click += new System.EventHandler(this.TìmKiếmToolStripMenuItem_Click);
            this.ChọnToolStripMenuItem.Click += new System.EventHandler(this.ChọnToolStripMenuItem_Click);
            //contextMenuStrip3
            this.thêmNhómToolStripMenuItem1.Click += new System.EventHandler(this.thêmNhómToolStripMenuItem1_Click);
            this.thêmChitiếtToolStripMenuItem1.Click += new System.EventHandler(this.thêmChitiếtToolStripMenuItem1_Click);

            //Buttons
            this.btnCapNhat.Click += new System.EventHandler(this.btnCapNhat_Click);
            this.btnXoa.Click += new System.EventHandler(this.btnXoa_Click);
            this.btnChon.Click += new System.EventHandler(this.btnChon_Click);
            this.btnThoat.Click += new System.EventHandler(this.btnThoat_Click);

            //listview control
            this.lvControl.View = System.Windows.Forms.View.Details;
            this.lvControl.AllowDrop = true;
            this.lvControl.HideSelection = false;
            this.lvControl.MultiSelect = false;
            this.lvControl.Font = new System.Drawing.Font("Times New Roman", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.lvControl.DragEnter += new System.Windows.Forms.DragEventHandler(this.lvControl_DragEnter);
            this.lvControl.DragDrop += new System.Windows.Forms.DragEventHandler(this.lvControl_DragDrop);
            this.lvControl.DragOver += new System.Windows.Forms.DragEventHandler(this.lvControl_DragOver);
            this.lvControl.MouseDown += new System.Windows.Forms.MouseEventHandler(this.lvControl_MouseDown);
            this.lvControl.DoubleClick += new System.EventHandler(this.lvControl_DoubleClick);
            this.lvControl.AfterLabelEdit += new System.Windows.Forms.LabelEditEventHandler(this.lvControl_AfterLabelEdit);
            this.lvControl.ColumnClick += new System.Windows.Forms.ColumnClickEventHandler(this.lvControl_ColumnClick);
            this.lvControl.ItemDrag += new System.Windows.Forms.ItemDragEventHandler(this.lvControl_ItemDrag);
            
            //treeview control
            this.tvControl.AllowDrop = true;
            this.tvControl.HideSelection = false;
            this.tvControl.DragDrop += new System.Windows.Forms.DragEventHandler(this.tvControl_DragDrop);
            this.tvControl.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(this.tvControl_AfterSelect);
            this.tvControl.MouseDown += new System.Windows.Forms.MouseEventHandler(this.tvControl_MouseDown);
            this.tvControl.DragEnter += new System.Windows.Forms.DragEventHandler(this.tvControl_DragEnter);
            this.tvControl.DragOver += new System.Windows.Forms.DragEventHandler(this.tvControl_DragOver);
        }

       
        #endregion


        private void frmDIADANH_Load(object sender, EventArgs e)
        {
            InitTreeView();
            InitListView();
            InitContextMenu();
        }

        #region "tvControl"

        #region "tvControl Functions"

        //Add node dau tien cua treeview
        public void FormatFirstNode(ref TreeNode node)
        {
            node.ForeColor = Color.Blue;
            //node.NodeFont = new Font(this.Font.Name, this.Font.Size + 1.0F, FontStyle.Bold);
            //node.NodeFont = new Font(this.Font, FontStyle.Bold);
            node.ImageIndex = 0;
            node.SelectedImageIndex = 0;
        }

        public void FormatChildNode(ref TreeNode node)
        {
            node.ForeColor = Color.DarkRed;
            //node.NodeFont = new Font(this.Font, FontStyle.Bold);
            node.ImageIndex = 0;
            node.SelectedImageIndex = 0;
        }

        public void InitTreeView()
        {
            tvControl.ContextMenuStrip = ContextMenuStrip2;
            //Lay danh muc tree view dau tien
            string strSQL;
            //strSQL = "select * from " + tableName + " where left(" + nhomColumnName + "," + lenNhom.ToString() + ") = '" + maNhom + "' and len(" + nhomColumnName + ") = (select min(len(" + nhomColumnName + ")) from " + tableName + ")"; //len(" + nhomColumnName + ") = (select min(len(" + nhomColumnName + ")) from " + tableName + ")
            strSQL = "select * from " + tableName + " where len(" + nhomColumnName + ") = (select min(len(" + nhomColumnName + ")) from " + tableName + ")";

            DataSet ds = MITI.BaseDB.Instance.ExecSql_DataSet(strSQL);
            
            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                //Add Node in Treeview
                TreeNode node = tvControl.Nodes.Add(dr[nhomColumnName].ToString(), dr[tenColumnName].ToString());

                //Kiem tra node co phai la node dau cua treeview khong
                //Neu bang thi cho mau xanh, nguoc lai mau do
                if (((bool)dr[cuoiColumnName] == false))
                {
                    //Tra ve node theo format dinh san
                    FormatFirstNode(ref node);
                }
                else
                {
                    //Tra ve node theo format dinh san
                    FormatChildNode(ref node);
                }
            }
            tvControl.Focus();
            tvControl.SelectedNode = tvControl.Nodes[0];
        }

        public void LoadTreeView(string nhomCha)
        {
            tvControl.ImageList = ImageList1;

            //Tim node co theo ten va tra ve kq
            TreeNode[] nodes = tvControl.Nodes.Find(nhomCha, true);
            TreeNode node;

            //Neu khong co node nao tim thay
            if (nodes.Length == 0)
            {
                return; 
            }

            //Lay node dau tien trong cac node tim thay
            node = nodes[0];

            //Neu node lay co cac node con thi xoa di
            if (node.Nodes.Count > 0)
            {
                node.Nodes.Clear();
            }

            //Lay cac node con theo node can tim
            DataTable db = CDIADANHCollection.LayTheoNhomCha_DataTable(nhomCha, 0);
            //Neu co node can tim co cac node con
            if (db.Rows.Count > 0)
            {
                //Tra ve node theo format dinh san
                if(node.Parent != null)
                    FormatChildNode(ref node);
                else
                    FormatFirstNode(ref node);
                
                foreach (DataRow dr in db.Rows)
                {
                    TreeNode childNode = node.Nodes.Add(dr[nhomColumnName].ToString(), dr[tenColumnName].ToString());
                    if (((bool)dr[cuoiColumnName] == false))
                    {
                        FormatChildNode(ref childNode);
                    }
                }
            }
        }

        public void HienThiGiaTriTimKiem(string nhomTimKiem)
        {
            TreeNode[] nodes = tvControl.Nodes.Find(nhomTimKiem, true);
            if (nodes.Length > 0)
            {
                tvControl.SelectedNode = nodes[0].Parent;
            }
            else
            {
                int maxlen = nhomTimKiem.Length;
                int len = lenNhom;
                while (len < maxlen)
                {
                    LoadTreeView(nhomTimKiem.Substring(0, len));
                    len += lenNhom;
                }
                //Neu nhomTimKiem co gia tri cuoi = False (tuc la hien thi tren TreeView) thi tim kiem tren TreeView
                //Nguoc lai se load Node Parent cua nhomTimKiem de tim kiem tren ListView
                if (CDIADANHCollection.LayGiaTriCuoiTheoNhom(nhomTimKiem) == false)
                {
                    nodes = tvControl.Nodes.Find(nhomTimKiem, true);
                    if (nodes.Length > 0)
                    {
                        tvControl.SelectedNode = nodes[0].Parent;
                    }
                }
                else
                {
                    nodes = tvControl.Nodes.Find(nhomTimKiem.Substring(0, nhomTimKiem.Length - lenNhom), true);
                    if (nodes.Length > 0)
                    {
                        tvControl.SelectedNode = nodes[0];
                    }
                }
            }
            ListViewItem[] items = lvControl.Items.Find(nhomTimKiem, true);
            if (items.Length > 0)
            {
                items[0].Selected = true;
            }
        }
        #endregion

        private void tvControl_AfterSelect(object sender, System.Windows.Forms.TreeViewEventArgs e)
        {
            string nhomCha = tvControl.SelectedNode.Name;
            if (tvControl.SelectedNode.GetNodeCount(false) == 0)
            {
                LoadTreeView(nhomCha);
            }
            LoadListView(nhomCha);
        }

        private void tvControl_DragDrop(object sender, System.Windows.Forms.DragEventArgs e)
        {
            if (e.Data.GetDataPresent("System.Windows.Forms.ListViewItem", false))
            {
                ListViewItem srcItem = (ListViewItem)e.Data.GetData("System.Windows.Forms.ListViewItem");
                Point pt;
                TreeNode destNode;
                pt = ((TreeView)sender).PointToClient(new Point(e.X, e.Y));
                destNode = ((TreeView)sender).GetNodeAt(pt.X, pt.Y);
                //SelectedNode cua Treeview chinh la parent node cua srcItem
                //nen kiem tra voi destNode co trung nhau ko
                if (object.ReferenceEquals(tvControl.SelectedNode, destNode))
                {
                    MessageBox.Show("Nơi chuyển đi và đến không được trùng nhau");
                    return; // TODO: might not be correct. Was : Exit Sub
                }

                DataRow objSrc;
                DataRow objDest;
                objSrc = CDIADANHCollection.LayTheoNhom_DataTable(srcItem.Name).Rows[0];
                objDest = CDIADANHCollection.LayTheoNhom_DataTable(destNode.Name).Rows[0];
                if (CDIADANHCollection.IsExists(objDest[nhomColumnName].ToString(), objSrc[tenColumnName].ToString(), 0))
                {
                    MessageBox.Show("'" + objSrc[tenColumnName] + "' này đã tồn tại trong nhóm '" + objDest[tenColumnName] + "'");
                    return; // TODO: might not be correct. Was : Exit Sub
                }

                //Kiem tra chieu dai Nhom co thoa khong
                if ((bool)objSrc[cuoiColumnName] == false)
                {
                    if (!CDIADANHCollection.KiemTraLengthChuyenDoiNhom(objSrc[nhomColumnName].ToString(), objDest[nhomColumnName].ToString()))
                    {
                        MessageBox.Show("Không thể chuyển toàn bộ nhóm '" + objSrc[tenColumnName] + "' sang nhóm '" + objDest[tenColumnName] + "'");
                        return;
                    }
                }

                if (MessageBox.Show("Bạn có muốn chuyển '" + objSrc[tenColumnName] + "' sang nhóm '" + objDest[tenColumnName] + "'", "Thông báo", MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    //Chuyen doi ma moi va tra ve ma moi
                    objSrc[nhomColumnName] = CDIADANHCollection.ChuyenDoiNhom(objSrc[nhomColumnName].ToString(), objDest[nhomColumnName].ToString());
                    //Refresh TreeView
                    //Cap nhat lai gia tri cuoi node dang chon o TreeView
                    //sau khi di chuyen Item o LisView
                    if (!CDIADANHCollection.IsExistsChildNodes(tvControl.SelectedNode.Name, false))
                    {
                        DataTable db = CDIADANHCollection.LayTheoNhom_DataTable(tvControl.SelectedNode.Name);
                        db.Rows[0][cuoiColumnName] = true;
                        CDIADANHCollection.Update(db.Rows[0]);
                    }
                    //Refresh TreeView tai noi chuyen di
                    LoadTreeView(tvControl.SelectedNode.Name);
                    //Refresh ListView
                    LoadListView(tvControl.SelectedNode.Name);
                    
                    //Cap nhat cuoi = false cho noi chuyen den
                    objDest[cuoiColumnName] = false;
                    CDIADANHCollection.Update(objDest);
                    //Refresh TreeView cho noi chuyen den
                    LoadTreeView(objDest[nhomColumnName].ToString());
                }
            }
            else if (e.Data.GetDataPresent("System.Windows.Forms.TreeNode", false))
            {
                TreeNode srcNode = (TreeNode)e.Data.GetData("System.Windows.Forms.TreeNode");
                TreeNode destNode;
                Point pt = ((TreeView)sender).PointToClient(new Point(e.X, e.Y));
                destNode = ((TreeView)sender).GetNodeAt(pt.X, pt.Y);
                if (object.ReferenceEquals(srcNode.Parent, destNode))
                {
                    MessageBox.Show("Nơi chuyển đi và đến không được trùng nhau");
                    return; // TODO: might not be correct. Was : Exit Sub
                }
                DataRow objSrc;
                DataRow objDest;
                objSrc = CDIADANHCollection.LayTheoNhom_DataTable(srcNode.Name).Rows[0];
                objDest = CDIADANHCollection.LayTheoNhom_DataTable(destNode.Name).Rows[0];
                if (CDIADANHCollection.IsExists(objDest[nhomColumnName].ToString(), objSrc[tenColumnName].ToString(), 0))
                {
                    MessageBox.Show("'" + objSrc[tenColumnName] + "' này đã tồn tại trong nhóm '" + objDest[tenColumnName] + "'");
                    return; // TODO: might not be correct. Was : Exit Sub
                }

                //Kiem tra chieu dai Nhom co thoa khong
                if ((bool)objSrc[cuoiColumnName] == false)
                {
                    if (!CDIADANHCollection.KiemTraLengthChuyenDoiNhom(objSrc[nhomColumnName].ToString(), objDest[nhomColumnName].ToString()))
                    {
                        MessageBox.Show("Không thể chuyển toàn bộ nhóm '" + objSrc[tenColumnName] + "' sang nhóm '" + objDest[tenColumnName] + "'");
                        return;
                    }
                }

                if (MessageBox.Show("Bạn có muốn chuyển '" + objSrc[tenColumnName] + "' sang nhóm '" + objDest[tenColumnName] + "'", "Thông báo", MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    //Chuyen doi ma moi va tra ve ma moi
                    objSrc[nhomColumnName] = CDIADANHCollection.ChuyenDoiNhom(objSrc[nhomColumnName].ToString(), objDest[nhomColumnName].ToString());
                    //Refesh TreeView
                    //Cap nhat lai gia tri cuoi neu ko co childNode
                    if (!CDIADANHCollection.IsExistsChildNodes(srcNode.Parent.Name, false))
                    {
                        DataTable db = CDIADANHCollection.LayTheoNhom_DataTable(srcNode.Parent.Name);
                        db.Rows[0][cuoiColumnName] = true;
                        CDIADANHCollection.Update(db.Rows[0]);
                    }
                    LoadTreeView(srcNode.Parent.Name);
                    //Cap nhat cuoi = false cho noi chuyen den
                    objDest[cuoiColumnName] = false;
                    CDIADANHCollection.Update(objDest);
                    LoadTreeView(objDest[nhomColumnName].ToString());
                    //Refresh ListView
                    LoadListView(tvControl.SelectedNode.Name);
                }
            }
        }

        private void tvControl_DragEnter(object sender, System.Windows.Forms.DragEventArgs e)
        {
            if (e.Data.GetDataPresent("System.Windows.Forms.ListViewItem") | e.Data.GetDataPresent("System.Windows.Forms.TreeNode"))
            {
                if ((e.KeyState & CtrlMask) == CtrlMask)
                {
                    e.Effect = DragDropEffects.Copy;
                }
                else
                {
                    e.Effect = DragDropEffects.Move;
                }
            }
            else
            {
                e.Effect = DragDropEffects.None;
            }
        }

        public void KiemTraDragDrop(ref System.Windows.Forms.DragEventArgs e, string destKey, string srcKey)
        {
            //Kiem tra trang thai move hay copy (CtrlMask = 8 (1000) , e.KeyState = 1 (0001) hoac 9 (1001))
            if ((e.KeyState & CtrlMask) == CtrlMask)
            {
                e.Effect = DragDropEffects.Copy;
            }
            else
            {
                e.Effect = DragDropEffects.Move;
            }

            //Kiem tra xem noi di va noi den co trung lap khong
            //1. Noi di trung voi noi den
            if (destKey == srcKey)
            {
                e.Effect = DragDropEffects.None;
            }
            //2. Noi den chua noi di (==> des length = src length + 3)
            else if (destKey.Length < srcKey.Length)
            {
                if (srcKey.Substring(0, srcKey.Length - 3) == destKey)
                    e.Effect = DragDropEffects.None;
            }
        }

        private void tvControl_DragOver(object sender, System.Windows.Forms.DragEventArgs e)
        {
            if (e.Data.GetDataPresent("System.Windows.Forms.ListViewItem"))
            {
                TreeNode destNode;
                Point pt = ((TreeView)sender).PointToClient(new Point(e.X, e.Y));
                destNode = ((TreeView)sender).GetNodeAt(pt.X, pt.Y);
                ListViewItem srcItem = (ListViewItem)e.Data.GetData(typeof(ListViewItem));
                if (destNode != null)
                {
                    KiemTraDragDrop(ref e, destNode.Name, srcItem.Name);
                }
                else
                {
                    e.Effect = DragDropEffects.None;
                }
            }
            else if (e.Data.GetDataPresent("System.Windows.Forms.TreeNode"))
            {
                TreeNode destNode;
                Point pt = ((TreeView)sender).PointToClient(new Point(e.X, e.Y));
                destNode = ((TreeView)sender).GetNodeAt(pt.X, pt.Y);
                TreeNode srcNode = (TreeNode)e.Data.GetData(typeof(TreeNode));
                if (destNode != null)
                {
                    KiemTraDragDrop(ref e, destNode.Name, srcNode.Name);
                }
                else
                {
                    e.Effect = DragDropEffects.None;
                }
            }
            else
            {
                e.Effect = DragDropEffects.None;
            }
        }

        private void tvControl_ItemDrag(object sender, System.Windows.Forms.ItemDragEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                DoDragDrop(e.Item, DragDropEffects.Move | DragDropEffects.Copy);
            }
        }

        private void tvControl_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                Point ClickPoint = new Point(e.X, e.Y);
                ListViewItem item = lvControl.GetItemAt(ClickPoint.X, ClickPoint.Y);
                {
                    if (item == null)
                    {
                        ContextMenuStrip1.Items["XóaToolStripMenuItem"].Visible = false;
                        ContextMenuStrip1.Items["ToolStripSeparator1"].Visible = false;
                    }
                    else
                    {
                        ContextMenuStrip1.Items["XóaToolStripMenuItem"].Visible = true;
                        ContextMenuStrip1.Items["ToolStripSeparator1"].Visible = true;
                        ContextMenuStrip1.Items["CậpNhậtToolStripMenuItem"].Visible = true;
                    }

                    // Convert from Tree coordinates to Screen coordinates
                    Point ScreenPoint = lvControl.PointToScreen(ClickPoint);
                    // Convert from Screen coordinates to Formc coordinates
                    Point FormPoint = this.PointToClient(ScreenPoint);
                    //Show context menu
                    ContextMenuStrip1.Show(this, FormPoint);
                }
            }
        }
        #endregion

        #region "lvControl"

        #region "lvControl Functions"
        public void InitListView()
        {
            lvControl.ContextMenuStrip = ContextMenuStrip1;
            lvControl.SmallImageList = ImageList1;
            lvControl.Columns.Add("Tên " + name, lvControl.Width - 22, HorizontalAlignment.Left);
            lvControl.Columns.Add("Cuoi", 0, HorizontalAlignment.Center);
        }

        public void LoadListView(string nhomCha)
        {
            lvControl.Items.Clear();
            DataTable db = CDIADANHCollection.LayTheoNhomCha_DataTable(nhomCha);
            ListViewItem item;
            foreach (DataRow dr in db.Rows)
            {
                item = new ListViewItem(dr[tenColumnName].ToString());
                if ((bool)dr[cuoiColumnName] == false)
                {
                    item.ImageIndex = 0;
                }
                else
                {
                    item.ImageIndex = 1;
                }
                ListViewItem.ListViewSubItem subItem = new ListViewItem.ListViewSubItem();
                subItem.Name = cuoiColumnName;
                //key of SubItem
                subItem.Text = dr[cuoiColumnName].ToString();
                item.SubItems.Add(subItem);
                item.Name = dr[nhomColumnName].ToString();
                lvControl.Items.Add(item);
            }
            //Count
            int folder = 0;
            int file = 0;
            CDIADANHCollection.CountChildNodes(nhomCha, ref folder, ref file);
            CountToolStripStatusLabel.Text = folder.ToString() + " Nhóm, " + file.ToString() + " " + name;
        }
        #endregion

        private void lvControl_AfterLabelEdit(object sender, System.Windows.Forms.LabelEditEventArgs e)
        {
            // Determine if label is changed by checking to see if it is equal to Nothing.
            if (e.Label == null)
            {
                return;
            }
            if (lvControl.SelectedItems.Count > 0)
            {
                string nhomCha = "";
                nhomCha = tvControl.SelectedNode.Name;
                int cuoi = (lvControl.SelectedItems[0].SubItems[cuoiColumnName].Text == "False" ? 0 : 1);
                if (CDIADANHCollection.IsExists(nhomCha, e.Label, cuoi))
                {
                    MessageBox.Show("Tên '" + e.Label + "' này đã có.");
                    e.CancelEdit = true;
                    lvControl.SelectedItems[0].BeginEdit();
                    return; // TODO: might not be correct. Was : Exit Sub
                }
                if (e.Label != null)
                {
                    CDIADANH obj = CDIADANHCollection.LayTheoNhom(lvControl.SelectedItems[0].Name);
                    obj.TEN_DIADANH = e.Label;
                    CDIADANHCollection.Update(obj);
                    lvControl.LabelEdit = false;
                }
                LoadTreeView(nhomCha);
            }
        }

        private void lvControl_ColumnClick(object sender, System.Windows.Forms.ColumnClickEventArgs e)
        {
            // Determine if the clicked column is already the column that is
            // being sorted.
            if ((e.Column == lvwColumnSorter.SortColumn))
            {
                // Reverse the current sort direction for this column.
                if ((lvwColumnSorter.Order == SortOrder.Ascending))
                {
                    lvwColumnSorter.Order = SortOrder.Descending;
                }
                else
                {
                    lvwColumnSorter.Order = SortOrder.Ascending;
                }
            }
            else
            {
                // Set the column number that is to be sorted; default to ascending.
                lvwColumnSorter.SortColumn = e.Column;
                lvwColumnSorter.Order = SortOrder.Ascending;
            }

            // Perform the sort with these new sort options.
            this.lvControl.Sort();
        }

        private void lvControl_DoubleClick(object sender, System.EventArgs e)
        {
            if (CDIADANHCollection.LayTheoNhom(lvControl.SelectedItems[0].Name).CUOI == false)
            {
                foreach (TreeNode node in tvControl.SelectedNode.Nodes)
                {
                    if (node.Name == lvControl.SelectedItems[0].Name)
                    {
                        tvControl.SelectedNode = node;
                        break; // TODO: might not be correct. Was : Exit For
                    }
                }
                tvControl.SelectedNode.Expand();
            }
            else
            {
                LoadListView(lvControl.SelectedItems[0].Name);
            }
        }

        private void lvControl_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                Point ClickPoint = new Point(e.X, e.Y);
                ListViewItem item = lvControl.GetItemAt(ClickPoint.X, ClickPoint.Y);
                {
                    if (item == null)
                    {
                        ContextMenuStrip1.Items["XóaToolStripMenuItem"].Visible = false;
                        ContextMenuStrip1.Items["ToolStripSeparator1"].Visible = false;
                        ContextMenuStrip1.Items["CậpNhậtToolStripMenuItem"].Visible = false;
                        ContextMenuStrip1.Items["ChọnToolStripMenuItem"].Visible = false;
                    }
                    else
                    {
                        ContextMenuStrip1.Items["XóaToolStripMenuItem"].Visible = true;
                        ContextMenuStrip1.Items["ToolStripSeparator1"].Visible = true;
                        ContextMenuStrip1.Items["CậpNhậtToolStripMenuItem"].Visible = true;
                        if (fCallForm != null)
                            ContextMenuStrip1.Items["ChọnToolStripMenuItem"].Visible = true;
                    }

                    // Convert from Tree coordinates to Screen coordinates
                    Point ScreenPoint = lvControl.PointToScreen(ClickPoint);
                    // Convert from Screen coordinates to Formc coordinates
                    Point FormPoint = this.PointToClient(ScreenPoint);
                    //Show context menu
                    ContextMenuStrip1.Show(this, FormPoint);
                }
            }
        }

        #region "ListView Drag Drop"
        private void lvControl_DragEnter(object sender, System.Windows.Forms.DragEventArgs e)
        {
            if (e.Data.GetDataPresent("System.Windows.Forms.ListViewItem") | e.Data.GetDataPresent("System.Windows.Forms.TreeNode"))
            {
                if ((e.KeyState & CtrlMask) == CtrlMask)
                {
                    e.Effect = DragDropEffects.Copy;
                }
                else
                {
                    e.Effect = DragDropEffects.Move;
                }
            }
            else
            {
                e.Effect = DragDropEffects.None;
            }
        }

        private void lvControl_DragDrop(object sender, System.Windows.Forms.DragEventArgs e)
        {
            if (e.Data.GetDataPresent("System.Windows.Forms.ListViewItem", false))
            {
                ListViewItem srcItem = (ListViewItem)e.Data.GetData("System.Windows.Forms.ListViewItem");
                Point pt;
                ListViewItem destItem;
                pt = ((ListView)sender).PointToClient(new Point(e.X, e.Y));
                destItem = ((ListView)sender).GetItemAt(pt.X, pt.Y);

                DataRow objSrc;
                DataRow objDest;
                objSrc = CDIADANHCollection.LayTheoNhom_DataTable(srcItem.Name).Rows[0];
                objDest = CDIADANHCollection.LayTheoNhom_DataTable(destItem.Name).Rows[0];
                //Kiểm tra xem nơi chuyển đến có tồn tại objSrc chưa
                if (CDIADANHCollection.IsExists(objDest[nhomColumnName].ToString(), objSrc[tenColumnName].ToString(), 0))
                {
                    MessageBox.Show("'" + objSrc[tenColumnName] + "' này đã tồn tại trong nhóm '" + objDest[tenColumnName] + "'");
                    return; // TODO: might not be correct. Was : Exit Sub
                }

                //Kiem tra chieu dai Nhom co thoa khong
                if ((bool)objSrc[cuoiColumnName] == false)
                {
                    if (!CDIADANHCollection.KiemTraLengthChuyenDoiNhom(objSrc[nhomColumnName].ToString(), objDest[nhomColumnName].ToString()))
                    {
                        MessageBox.Show("Không thể chuyển toàn bộ nhóm '" + objSrc[tenColumnName] + "' sang nhóm '" + objDest[tenColumnName] + "'");
                        return;
                    }
                }

                if (MessageBox.Show("Bạn có muốn chuyển '" + objSrc[tenColumnName] + "' sang nhóm '" + objDest[tenColumnName] + "'", "Thông báo", MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    //Chuyen doi ma moi va tra ve ma moi
                    CDIADANHCollection.ChuyenDoiNhom(objSrc[nhomColumnName].ToString(), objDest[nhomColumnName].ToString());
                    //Refresh TreeView
                    //Cap nhat cuoi = false cho noi chuyen den
                    objDest[cuoiColumnName] = false;
                    CDIADANHCollection.Update(objDest);
                    //Refresh TreeView
                    LoadTreeView(tvControl.SelectedNode.Name);
                    //Refresh ListView
                    LoadListView(tvControl.SelectedNode.Name);
                }
            }
            else if (e.Data.GetDataPresent("System.Windows.Forms.TreeNode", false))
            {
                TreeNode srcNode = (TreeNode)e.Data.GetData("System.Windows.Forms.TreeNode");
                Point pt;
                ListViewItem destItem;
                pt = ((ListView)sender).PointToClient(new Point(e.X, e.Y));
                destItem = ((ListView)sender).GetItemAt(pt.X, pt.Y);
                if (destItem == null)
                {
                    // Trường hợp chọn chuyển vào ListView mà ko chọn Item cụ thể nào
                    DataRow dr = CDIADANHCollection.LayTheoNhom_DataTable(tvControl.SelectedNode.Name).Rows[0];
                    //Lay tam mot item roi gan gia tri moi vao
                    destItem = new ListViewItem(dr[tenColumnName].ToString());
                    destItem.SubItems.Add("");
                    destItem.SubItems.Add("");
                    destItem.SubItems.Add("");
                    destItem.Name = dr[tenColumnName].ToString();
                    //Nếu chuyển vào ListView mà không chọn Item cụ thể thì có 2 trường hợp:
                    //**TH1: srcNode chuyển vào ngay trong thư mục của chính nó
                    //**Th2: srcNode có thư mục cha trùng với thư mục cha của nơi chuyển đến
                    if ((object.ReferenceEquals(srcNode, tvControl.SelectedNode)) || (object.ReferenceEquals(srcNode.Parent, tvControl.SelectedNode)))
                    {
                        MessageBox.Show("Nơi chuyển đi và nơi chuyển đến không được trùng nhau");
                        return; // TODO: might not be correct. Was : Exit Sub
                    }
                }
                else
                {
                    if (object.ReferenceEquals(srcNode.Parent, tvControl.SelectedNode.Nodes[destItem.Name]))
                    {
                        MessageBox.Show("Nơi chuyển đi và nơi chuyển đến không được trùng nhau");
                        return; // TODO: might not be correct. Was : Exit Sub
                    }
                }

                DataRow objSrc;
                DataRow objDest;
                objSrc = CDIADANHCollection.LayTheoNhom_DataTable(srcNode.Name).Rows[0];
                objDest = CDIADANHCollection.LayTheoNhom_DataTable(destItem.Name).Rows[0];
                if (CDIADANHCollection.IsExists(objDest[nhomColumnName].ToString(), objSrc[tenColumnName].ToString(), 0))
                {
                    MessageBox.Show("'" + objSrc[tenColumnName] + "' này đã tồn tại trong nhóm '" + objDest[tenColumnName] + "'");
                    return; // TODO: might not be correct. Was : Exit Sub
                }

                //Kiem tra chieu dai Nhom co thoa khong
                if ((bool)objSrc[cuoiColumnName] == false)
                {
                    if (!CDIADANHCollection.KiemTraLengthChuyenDoiNhom(objSrc[nhomColumnName].ToString(), objDest[nhomColumnName].ToString()))
                    {
                        MessageBox.Show("Không thể chuyển toàn bộ nhóm '" + objSrc[tenColumnName] + "' sang nhóm '" + objDest[tenColumnName] + "'");
                        return;
                    }
                }

                if (MessageBox.Show("Bạn có muốn chuyển '" + objSrc[tenColumnName] + "' sang nhóm '" + objDest[tenColumnName] + "'", "Thông báo", MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    //Chuyen doi ma moi va tra ve ma moi
                    CDIADANHCollection.ChuyenDoiNhom(objSrc[nhomColumnName].ToString(), objDest[nhomColumnName].ToString());
                    //Refresh TreeView
                    //Cap nhat lai gia tri cuoi neu ko co childNode
                    if (!CDIADANHCollection.IsExistsChildNodes(srcNode.Parent.Name, false))
                    {
                        DataTable db = CDIADANHCollection.LayTheoNhom_DataTable(srcNode.Parent.Name);
                        db.Rows[0][cuoiColumnName] = true;
                        CDIADANHCollection.Update(db.Rows[0]);
                    }
                    LoadTreeView(srcNode.Parent.Name);
                    //Cap nhat cuoi = false cho noi chuyen den
                    objDest[cuoiColumnName] = false;
                    CDIADANHCollection.Update(objDest);
                    LoadTreeView(objDest[nhomColumnName].ToString());
                    //Refresh ListView
                    LoadListView(tvControl.SelectedNode.Name);
                }
            }
        }

        private void lvControl_DragOver(object sender, System.Windows.Forms.DragEventArgs e)
        {
            if (e.Data.GetDataPresent("System.Windows.Forms.ListViewItem"))
            {
                ListViewItem destItem;
                Point pt = ((ListView)sender).PointToClient(new Point(e.X, e.Y));
                destItem = ((ListView)sender).GetItemAt(pt.X, pt.Y);
                ListViewItem srcItem = (ListViewItem)e.Data.GetData(typeof(ListViewItem));
                if (destItem != null)
                {
                    KiemTraDragDrop(ref e, destItem.Name, srcItem.Name);
                }
                else
                {
                    e.Effect = DragDropEffects.None;
                }
            }
            else if (e.Data.GetDataPresent("System.Windows.Forms.TreeNode"))
            {
                ListViewItem destItem;
                Point pt = ((ListView)sender).PointToClient(new Point(e.X, e.Y));
                destItem = ((ListView)sender).GetItemAt(pt.X, pt.Y);
                TreeNode srcNode = (TreeNode)e.Data.GetData(typeof(TreeNode));
                if (destItem != null)
                {
                    KiemTraDragDrop(ref e, destItem.Name, srcNode.Name);
                }
                else
                {
                    e.Effect = DragDropEffects.None;
                }
            }
            else
            {
                e.Effect = DragDropEffects.None;
            }
        }

        private void lvControl_ItemDrag(object sender, System.Windows.Forms.ItemDragEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                DoDragDrop(e.Item, DragDropEffects.Move | DragDropEffects.Copy);
            }
        }

        #endregion

        #endregion

        #region "Context Menu"
        public void InitContextMenu()
        {
            //Đổi lại tên cho phù hợp với danh mục cần gọi
            ContextMenuStrip1.Items["thêmChitiếtToolStripMenuItem"].Text = "Thêm " + name;
            contextMenuStrip3.Items["thêmChitiếtToolStripMenuItem1"].Text = "Thêm " + name;
        }

        public string TaoTenNhomMoi()
        {
            string strTenBanDau = "";
            strTenBanDau = "Nhóm mới";
            int count = 0;
            bool isStop = false;
            string strTenMoi = strTenBanDau;
            while (!isStop)
            {
                int i = 0;
                for (i = 0; i <= tvControl.SelectedNode.Nodes.Count - 1; i++)
                {
                    TreeNode node = tvControl.SelectedNode.Nodes[i];
                    if (strTenMoi == node.Text)
                    {
                        count += 1;
                        strTenMoi = strTenBanDau + " (" + count + ")";
                        break; 
                    }
                }
                if (i == tvControl.SelectedNode.Nodes.Count)
                {
                    isStop = true;
                }
            }
            return strTenMoi;
        }

        public string TaoTenMoi()
        {
            string strTenBanDau = "";
            strTenBanDau = "Tên " + name + " mới";
            int count = 0;
            bool isStop = false;
            string strTenMoi = strTenBanDau;
            while (!isStop)
            {
                int i = 0;
                for (i = 0; i <= lvControl.Items.Count - 1; i++)
                {
                    ListViewItem item = lvControl.Items[i];
                    if (strTenMoi == item.Text)
                    {
                        count += 1;
                        strTenMoi = strTenBanDau + " (" + count + ")";
                        break; 
                    }
                }
                if (i == lvControl.Items.Count)
                {
                    isStop = true;
                }
            }
            return strTenMoi;
        }

        private void ThêmChitiếtToolStripMenuItem_Click(object sender, System.EventArgs e)
        {
            string nhomCha = "";
            nhomCha = tvControl.SelectedNode.Name;
            if (nhomCha.Length == CDIADANHCollection.ColumnLength(nhomColumnName))
            {
                MessageBox.Show("Không thể thêm nhóm được nữa.");
                return; 
            }

            CDIADANH obj = new CDIADANH();
            obj.NHOM = CDIADANHCollection.TaoNhom(nhomCha);
            obj.TEN_DIADANH = TaoTenMoi();
            obj.CUOI = true;
            CDIADANHCollection.Insert(obj);
            LoadListView(nhomCha);
            lvControl.LabelEdit = true;
            lvControl.Items[obj.NHOM].BeginEdit();
        }

        private void ThêmNhómToolStripMenuItem_Click(object sender, System.EventArgs e)
        {
            string nhomCha = "";
            nhomCha = tvControl.SelectedNode.Name;
            if (nhomCha.Length == CDIADANHCollection.ColumnLength(nhomColumnName))
            {
                MessageBox.Show("Không thể thêm nhóm được nữa.");
                return;
            }

            CDIADANH cls = new CDIADANH();
            cls.NHOM = CDIADANHCollection.TaoNhom(nhomCha);
            cls.TEN_DIADANH = TaoTenNhomMoi();
            cls.CUOI = false;
            CDIADANHCollection.Insert(cls);
            LoadTreeView(nhomCha);
            LoadListView(nhomCha);
            lvControl.LabelEdit = true;
            lvControl.Items[cls.NHOM].BeginEdit();
        }

        private void QuayLạiToolStripMenuItem_Click(object sender, System.EventArgs e)
        {
            if (tvControl.SelectedNode.Parent != null)
            {
                tvControl.SelectedNode = tvControl.SelectedNode.Parent;
                LoadListView(tvControl.SelectedNode.Name);
            }
        }

        private void XóaToolStripMenuItem_Click(object sender, System.EventArgs e)
        {
            CDIADANH cls = CDIADANHCollection.LayTheoNhom(lvControl.SelectedItems[0].Name);
            if (CDIADANHCollection.IsExistsChildNodes(cls.NHOM, true))
            {
                string strMsg;
                strMsg = "Nhóm này đang chứa " + name + " không xóa được.";
                MessageBox.Show(strMsg);
            }
            else
            {
                if (MessageBox.Show("Bạn thật sự muốn xóa?","Thông báo", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Yes)
                {
                    CDIADANHCollection.DeleteByNhom(cls.NHOM, true);
                    lvControl.SelectedItems[0].Remove();
                    LoadTreeView(tvControl.SelectedNode.Name);
                }
            }
        }

        private void CậpNhậtToolStripMenuItem_Click(object sender, System.EventArgs e)
        {
            CDIADANH cls = CDIADANHCollection.LayTheoNhom(lvControl.SelectedItems[0].Name);
            lvControl.LabelEdit = true;
            lvControl.SelectedItems[0].BeginEdit();
        }

        private void TìmKiếmToolStripMenuItem_Click(object sender, System.EventArgs e)
        {
            frmTimKiem frm = new frmTimKiem(this);
            frm.ShowDialog();
        }

        private void TìmKiếmTreeViewToolStripMenuItem_Click(object sender, System.EventArgs e)
        {
            if (tvControl.SelectedNode == null)
            {
                frmTimKiem frm = new frmTimKiem(this);
                frm.ShowDialog();
            }
        }

        private void ChọnToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (fCallForm.Name == "frmNHANSU")
            {
                CDIADANH objDiaDanh = CDIADANHCollection.LayTheoNhom(lvControl.SelectedItems[0].Name);
                if (!objDiaDanh.CUOI)
                {
                    MessageBox.Show("Phải chọn ở mức phường(xã).");
                    return;
                }
                frmNHANSU frm = (frmNHANSU)fCallForm;
                frm.objDiaDanh = objDiaDanh;
            }
            else if (fCallForm.Name == "frmQHGiaDinh")
            {
                CDIADANH objDiaDanh = CDIADANHCollection.LayTheoNhom(lvControl.SelectedItems[0].Name);
                if (!objDiaDanh.CUOI)
                {
                    MessageBox.Show("Phải chọn ở mức phường(xã).");
                    return;
                }
                frmQHGiaDinh frm = (frmQHGiaDinh)fCallForm;
                frm.objDiaDanh = objDiaDanh;
            }
            this.Close();
        }

        #endregion

        #region "Buttons"

        private void btnThoat_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void thêmNhómToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            ThêmNhómToolStripMenuItem_Click(null, null);
        }

        private void thêmChitiếtToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            ThêmChitiếtToolStripMenuItem_Click(null, null);
        }

        private void btnCapNhat_Click(object sender, EventArgs e)
        {
            CậpNhậtToolStripMenuItem_Click(null, null);
        }

        private void btnXoa_Click(object sender, EventArgs e)
        {
            XóaToolStripMenuItem_Click(null, null);
        }

        private void btnChon_Click(object sender, EventArgs e)
        {
            ChọnToolStripMenuItem_Click(null, null);
        }
        #endregion

        private void btnThemMoi_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                Point ClickPoint = new Point(e.X, e.Y);
                //contextMenuStrip3.Items["thêmNhómToolStripMenuItem1"].Visible = true;
                //contextMenuStrip3.Items["thêmĐơnVịToolStripMenuItem1"].Visible = true;

                // Convert from Tree coordinates to Screen coordinates
                Point ScreenPoint = btnThemMoi.PointToScreen(ClickPoint);
                // Convert from Screen coordinates to Formc coordinates
                Point FormPoint = this.PointToClient(ScreenPoint);
                //Show context menu
                contextMenuStrip3.Show(this, FormPoint);
            }
        }

       
               
    }
}
